const util = require('../../../../../../utils/util.js');
const api = require('../../../../../../config/api.js');
const time = require('../../../../../../utils/time.js');

const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    platform: "",//客户端平台
    descDialog: { "show": false, "type": 0, "isShow": false },//文字描述
    circleid: '',//圈子id
    circleInfo: { "circleNotice": "", "circleNoticeLength": 0, "seedid": "", "seedname": "", "itemTypeIdentification": 0, "identificationXAxis": "", "identificationYAxis": "", "identificationAddress": "", "identificationName": "", "isSetContract": false, "addressOauhRefusedDialogShow": false, "projectdateIdentification": 0, "projectdateStartLimit": "", "projectdateEndLimit": "", "projectdateStart": "", "projectdateEnd": "", "preferentialdateStartMin": "", "preferentialdateEndMax": "", "validityStartMin": "", "validityEndMax": "", "returnMoneyText": "", "returnPrice": "", "returnPreferentialSettings": "", "returnAmountDetailSize": "", "returnItemTypeIdentification": "", "returnProjectdateStart": "", "returnProjectdateEnd": "", "returnProjectdateidentification": "", "calculateDifferDay": "" },//圈子信息
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var _this = this;
    var platform = wx.getSystemInfoSync().platform;
    _this.setData({
      platform: platform,
      circleid: options.circleid,
      ["descDialog.isShow"]: true
    })
    // 获取圈子设置信息
    _this.getInterestSet();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var _this = this;
    var isShow = _this.data.descDialog.isShow;
    if (isShow){
      _this.getAmountScope();
      _this.setData({
        ["descDialog.isShow"]: false
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 文字描述：打开
   */
  descDialogShow: function (e) {
    var _this = this;
    var type = e.currentTarget.dataset.type;
    var descDialog = { "show": true, "type": type };
    _this.setData({
      descDialog: descDialog
    })
  },

  /**
   * 文字描述：关闭
   */
  descDialogClose: function (e) {
    var _this = this;
    var descDialog = { "show": false, "type": 0 };
    _this.setData({
      descDialog: descDialog
    })
  },

  /**
   * 选择种子
   */
  navigateToGrowingSeeds: function () {
    var _this = this;
    wx.navigateTo({
      url: '../growingSeeds/growingSeeds?joinCount=' + _this.data.circleInfo.joinCount +'&seedid=' + _this.data.circleInfo.seedid + '&seedname=' + _this.data.circleInfo.seedname,
    })
  },

  /**
   * 圈子公告的输入事件
   */
  circleNoticeInput: function (e) {
    var _this = this;
    var value = e.detail.value.replace(/[\r\n]/g, ' ');
    var cursor = value.length;
    _this.setData({
      ["circleInfo.circleNotice"]: value,
      ["circleInfo.circleNoticeLength"]: cursor
    })
  },

  /**
   * 线上活动、线下活动切换
   */
  itemTypeIdentificationTap: function (e) {
    var _this = this;
    var type = e.currentTarget.dataset.type;
    _this.setData({
      ["circleInfo.itemTypeIdentification"]: type
    });
    if (type == 1){
      _this.setData({
        ["circleInfo.projectdateIdentification"]: 1
      })
    }
  },

  /**
   * 获取线下活动地址
   */
  getIdentificationName() {
    var _this = this;
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.userLocation']) {
          // 未授权
          wx.authorize({
            scope: 'scope.userLocation',
            success() {
              _this.getIdentificationNameStart();
            },
            fail: function () {
              // 拒绝授权
              _this.setData({
                ["circleInfo.addressOauhRefusedDialogShow"]: true
              })
            }
          })
        } else {
          // 已授权
          _this.getIdentificationNameStart();
        }
      }
    })
  },

  /**
   * 获取线下活动地址：开始
   */
  getIdentificationNameStart: function () {
    var _this = this;
    wx.chooseLocation({
      success: function (res) {
        _this.setData({
          ["circleInfo.identificationAddress"]: res.address,
          ["circleInfo.identificationName"]: res.name,
          ["circleInfo.identificationXAxis"]: res.latitude,
          ["circleInfo.identificationYAxis"]: res.longitude
        })
      }
    })
  },

  /**
   * 地址拒绝授权的提示弹窗关闭
   */
  addressOauhRefusedDialogClose: function () {
    var _this = this;
    _this.setData({
      ["circleInfo.addressOauhRefusedDialogShow"]: false
    })
  },

  /**
   * 地址拒绝授权的提示弹窗确认动作
   */
  addressOauhRefusedDialogSuccess: function () {
    var _this = this;
    wx.openSetting({
      success: function (data) {
        if (data.authSetting["scope.userLocation"] == true) {
          // 授权成功
          _this.addressOauhRefusedDialogClose();
        } else {
          // 授权失败
          _this.addressOauhRefusedDialogClose();
        }
      }
    })
  },

  /**
   * 校验圈子
   */
  checkCircleInfo: function () {
    var _this = this;
    var circleInfo = _this.data.circleInfo;
    var itemTypeIdentification = circleInfo.itemTypeIdentification;
    if (itemTypeIdentification == 1) {
      var identificationName = circleInfo.identificationName;
      if (identificationName == null || identificationName.length <= 0) {
        util.dialogAlert("请选择详细地址");
        return false;
      }
    }
    var projectdateIdentification = circleInfo.projectdateIdentification;
    if (projectdateIdentification == 1) {
      var projectdateStart = circleInfo.projectdateStart;
      if (projectdateStart == null || projectdateStart.lenght <= 0) {
        util.dialogAlert("请选择活动开始日期");
        return false;
      }
      var projectdateEnd = circleInfo.projectdateEnd;
      if (projectdateEnd == null || projectdateEnd.lenght <= 0) {
        util.dialogAlert("请选择活动结束日期");
        return false;
      }
    }
    if (!_this.checkProjectdate(circleInfo.projectdateStart, circleInfo.projectdateEnd)) {
      return false;
    }
    return true;
  },

  /**
   * 提交
   */
  submit: function (type = 0) {
    var _this = this;
    if (!_this.checkCircleInfo()) {
      return false;
    }
    var openid = app.globalData.logininfo.openid;
    if (openid != null && openid != "") {
      // 已登录
      var circleid = _this.data.circleid
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var param = {};
        param.access_token = res.access_token;
        param.openid = openid;
        param.circleid = circleid;
        param.circleInfo = JSON.stringify(_this.data.circleInfo);
        util.post(api.Interest_DoUpdateInterestSetApiUrl, param).then(function (res) {
          if (res.code == 200) {
            if(type == 1){
              _this.setData({
                ["descDialog.isShow"]: true
              })
              wx.navigateTo({
                url: '../../editdetails/registrationfee/registrationfee2?circleid=' + circleid,
              })
            }else{
              wx.navigateBack({
                delta: 1
              })
            }
          }
        })
      })
    }
  },

  /**
   * 获取圈子设置信息
   */
  getInterestSet: function () {
    var _this = this;
    var openid = app.globalData.logininfo.openid;
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var param = {};
        param.access_token = res.access_token;
        param.openid = openid;
        param.circleid = _this.data.circleid;
        util.post(api.Interest_GetInterestSetApiUrl, param).then(function (res) {
          if (res.code == 200) {
            var circleInfo = res.result.json;
            _this.setData({
              circleInfo: circleInfo
            })
            // 加载圈子付费设置的价格范围以及时间
            _this.getAmountScope();
          }
        })
      })
    }
  },

  /**
   * 活动日期切换时间
   */
  projectdateIdentificationTap: function (e) {
    var _this = this;
    var type = e.currentTarget.dataset.type;
    var itemTypeIdentification = _this.data.circleInfo.itemTypeIdentification;
    if (!(type == 0 && itemTypeIdentification == 1)){
      _this.setData({
        ["circleInfo.projectdateIdentification"]: type
      })
    }
  },

  /**
   * 活动开始日期选择时间
   */
  projectdateStartChange: function (e) {
    var _this = this;
    var projectdateStart = e.detail.dateString;
    var projectdateEnd = _this.data.circleInfo.projectdateEnd;
    if (projectdateStart > projectdateEnd) {
      projectdateEnd = util.getDateHHMMStr(projectdateStart, 1);
    }
    if (!_this.checkProjectdate(projectdateStart, projectdateEnd)) {
      return false;
    }
    _this.setData({
      ["circleInfo.projectdateStart"]: projectdateStart,
      ["circleInfo.projectdateEnd"]: projectdateEnd,
      ["circleInfo.projectdateEndLimit"]: projectdateEnd
    })
    _this.calculateDifferDay();
  },

  /**
   * 活动结束日期选择时间
   */
  projectdateEndChange: function (e) {
    var _this = this;
    var projectdateEnd = e.detail.dateString;
    var projectdateStart = _this.data.circleInfo.projectdateStart;
    if (projectdateStart > projectdateEnd) {
      util.dialogAlert("不能小于开始时间");
      return false;
    }
    if (!_this.checkProjectdate(projectdateStart, projectdateEnd)) {
      return false;
    }
    _this.setData({
      ["circleInfo.projectdateEnd"]: projectdateEnd
    })
    _this.calculateDifferDay();
  },

  /**
   * 校验项目时间
   */
  checkProjectdate: function (projectdateStart, projectdateEnd) {
    var _this = this;
    var circleInfo = _this.data.circleInfo;
    var preferentialdateStartMin = circleInfo.preferentialdateStartMin;
    var preferentialdateEndMax = circleInfo.preferentialdateEndMax;
    var validityStartMin = circleInfo.validityStartMin;
    var validityEndMax = circleInfo.validityEndMax;
    if (preferentialdateStartMin != null && preferentialdateStartMin.length > 0 && preferentialdateStartMin < projectdateStart) {
      util.dialogAlert("票种最小的优惠开始时间为：\r\n" + preferentialdateStartMin);
      return false;
    }
    if (preferentialdateEndMax != null && preferentialdateEndMax.length > 0 && preferentialdateEndMax > projectdateEnd) {
      util.dialogAlert("票种最大的优惠结束时间为：\r\n" + preferentialdateEndMax);
      return false;
    }
    if (validityStartMin != null && validityStartMin.length > 0 && validityStartMin < projectdateStart) {
      util.dialogAlert("契约最小的开始时间为：\r\n" + validityStartMin);
      return false;
    }
    if (validityEndMax != null && validityEndMax.length > 0 && validityEndMax > projectdateEnd) {
      util.dialogAlert("契约最大的结束时间为：\r\n" + validityEndMax);
      return false;
    }
    return true;
  },

  /**
   * 去契约金页面
   */
  navigateToCreatecontract: function () {
    var _this = this;
    wx.navigateTo({
      url: '../../editdetails/createcontract/createcontract?circleid=' + _this.data.circleid
    })
  },

  /**
   * 去报名费和分销佣金页面
   */
  navigateToRegistrationfee: function () {
    var _this = this;
    _this.submit(1);
  },

  /**
   * 获取圈子付费设置的价格范围
   */
  getAmountScope: function(){
    var _this = this;
    var openid = app.globalData.logininfo.openid;
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var param = {};
        param.access_token = res.access_token;
        param.openid = openid;
        param.circleid = _this.data.circleid;
        util.post(api.Interest_GetAmountScopeApi, param).then(function (res) {
          if (res.code == 200) {
            var interestData = res.result.interestData;
            _this.setData({
              ["circleInfo.returnMoneyText"]: interestData.returnMoneyText,
              ["circleInfo.returnPrice"]: interestData.returnPrice,
              ["circleInfo.returnPreferentialSettings"]: interestData.returnPreferentialSettings,
              ["circleInfo.returnAmountDetailSize"]: interestData.returnAmountDetailSize,
              ["circleInfo.returnItemTypeIdentification"]: interestData.returnItemTypeIdentification,
              ["circleInfo.returnProjectdateStart"]: interestData.returnProjectdateStart,
              ["circleInfo.returnProjectdateEnd"]: interestData.returnProjectdateEnd,
              ["circleInfo.projectdateStart"]: interestData.projectdateStartStr,
              ["circleInfo.projectdateEnd"]: interestData.projectdateEndStr,
              ["circleInfo.projectdateStartLimit"]: interestData.projectdateStartLimit,
              ["circleInfo.projectdateEndLimit"]: interestData.projectdateEndLimit,
              ["circleInfo.returnProjectdateidentification"]: interestData.returnProjectdateidentification,
              ["circleInfo.preferentialdateStartMin"]: interestData.preferentialdateStartMin,
              ["circleInfo.preferentialdateEndMax"]: interestData.preferentialdateEndMax,
              ["circleInfo.validityStartMin"]: interestData.validityStartMin,
              ["circleInfo.validityEndMax"]: interestData.validityEndMax,
            })
            _this.calculateDifferDay();
          }
        })
      })
    }
  },

  /**
   * 计算两个时间
   */
  calculateDifferDay: function(){
    var _this = this;
    var projectdateStart = _this.data.circleInfo.projectdateStart;
    var projectdateEnd = _this.data.circleInfo.projectdateEnd;
    if (projectdateStart.length > 0 && projectdateEnd.length > 0) {
      var date1 = projectdateEnd.split(" ")[0];
      var date2 = projectdateStart.split(" ")[0];
      var calculateDifferDay = time.calculateDifferDay(date1,date2);
      _this.setData({
        ["circleInfo.calculateDifferDay"]: calculateDifferDay
      })
    }
  },
})